import { useEffect, useState } from 'react';
import './index.scss'
import '../../style/title.scss'
import { View } from '@tarojs/components';
import ConsultantCard, { ConsultantCardProps } from '../../components/Card/ConsultantCard';
import Taro from '@tarojs/taro';
import { consultInfo } from '../../configProvider/backendInterface';
import { pinyin } from 'pinyin-pro';
import { IP_NAME } from '../../configProvider/namespace';
const ConsultantList = () => {
  const [conList, setConList] = useState<consultInfo[]>([]);
  useEffect(() => {
    Taro.getStorage({
      key: 'token',
      success: (token) => {
        console.log(token)
        getConList(token.data)
      }
    })
  }, [])
  const getConList = (token: string) => {
    Taro.request({
      url: `${IP_NAME}/counselor/getAvailableCounselor?page=1&size=10&order=id asc&token=${token}`,
      data: {
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res.data)
        setConList(res.data.data.items)
      }
    })
  }
  const startChat = async (consultant: consultInfo) => {
    console.log(consultant);
    Taro.setStorage({
      key: 'consultant',
      data: consultant
    })

    Taro.showModal({
      title: `确认选择咨询师"${consultant.name}"?`,
      success: async function (res) {
        if (res.confirm) {
          Taro.getStorage({
            key: 'myInfo',
            success: (res) => {
              console.log('myInfo', res.data)
              // if (consultant.consulted === '已咨询') {
              //   console.log('groupID', pinyin(`GROUP${consultant.name}${res.data.name}null`, { toneType: 'none', type: 'array' }).join(''))
              Taro.setStorage({
                key: 'groupID',
                data: pinyin(`${consultant.name}${res.data.name}null`, { toneType: 'none', type: 'array' }).join('')
              })
              Taro.setStorage({
                key: 'conversationID',
                data: pinyin(`GROUP${consultant.name}${res.data.name}null`, { toneType: 'none', type: 'array' }).join('')
                // data: 'GROUPguapiwangerkenull'
              })

              Taro.request({
                url: `${IP_NAME}/userSig?imid=${res.data.openid}&name=${res.data.name}`,
                header: {
                  'content-type': 'application/json'
                },
                success: function (res) {
                  console.log('get userSig', res.data)
                }
              })
              Taro.request({
                url: `${IP_NAME}/im/import?imid=${res.data.openid}`,
                data: {},
                header: {
                  'content-type': 'application/json'
                },
                success: function (res0) {
                  console.log('import', res0.data)
                  createGroup(consultant.name, res.data.name, res.data.openid, consultant.imid)
                }
              })
            }
          })

        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    })
  }
  const createGroup = (consultantName: string, userName: string, ownerImid: string, consultantImid: string) => {
    // console.log('ownerImid', ownerImid);

    Taro.request({
      url: `${IP_NAME}/im/group/create?name=${consultantName}${userName}&owner=${ownerImid}`,
      data: {},
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log('create', res.data)
        console.log('create GroupId', res.data.GroupId)
        console.log('consultantImid', consultantImid)
        let groupID = res.data.GroupId ?? `${consultantName}${userName}null`
        Taro.request({
          url: `${IP_NAME}/im/group/add_member?group_id=${groupID}&member=${ownerImid}`,
          data: {},
          header: {
            'content-type': 'application/json'
          },
          success: (res01) => {
            console.log('add_member', res01.data)
            Taro.request({
              url: `${IP_NAME}/im/group/add_member?group_id=${groupID}&member=${consultantImid}`,
              data: {},
              header: {
                'content-type': 'application/json'
              },
              success: function (res0) {
                console.log('add_member', res0.data)
                console.log('ownerImid', ownerImid)
                sendAndStart(res.data.GroupId, ownerImid);
                sendAndStart(res.data.GroupId, consultantImid);
                Taro.setStorage({
                  key: 'conversationID',
                  data: pinyin(`GROUP${groupID}`, { toneType: 'none', type: 'array' }).join('')
                  // data: 'GROUP@TGS#2Y2M4MYM6'
                }).then(() => {
                  Taro.request({
                    method: 'POST',
                    url: `${IP_NAME}/conversation/start`,
                    data: {
                      counselor: consultantName,
                      user: userName
                    },
                    header: {
                      'content-type': 'application/json'
                    },
                    success: function (res) {
                      console.log(res.data)
                      Taro.setStorage({
                        key: "chatId",
                        data: res.data.data.id
                      })
                    }
                  })
                  Taro.navigateTo({ url: '../TUIChat/index' });
                })
              }
            })
          }
        })
      }
    })
  }
  const sendAndStart = (groupId: string, imid: string) => {
    Taro.request({
      url: `${IP_NAME}/im/group/text?group_id=${groupId}&imid=${imid}`,
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res.data)
      }
    })
  }
  return <>
    <View className='common-title'>选择咨询师</View>
    <View className='consultant-list'>
      {conList.map((value) => {
        return <ConsultantCard cid={value.id} portrait={value.avatar} name={value.name}
          visited={value.consulted} score={value.rating}
          state={value.busy} onClick={() => startChat(value)} />
      })}
    </View>
  </>
}
export default ConsultantList;
